<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Member;
use App\Realname;
use App\ShopHistory;
use App\Withdraw;
use App\Services\AliTiXian;
use App\Services\Daifu;
use App\Account;
use App\AliPreBuy;

class MoneyController extends AdminController
{

    private $_type = array(
        '1' => '充值',
        '2' => '提现',
        '3' => '还款',
        '4' => '付款',
        '5' => '转账',
        '6' => '网购',
        '7' => '退款',
        '8' => '手动加',
        '9' => '手动减',
        '10' => '订单收入',
        '11' => '订单退款',
        '12' => '订单收入冻结',
        '13' => '订单收入解冻'
    );

    /**
     * 用户余额--列表
     *
     * @param Request $request
     */
    public function moneylist(Request $request)
    {
        $name = trim($request->input('name', ''));
        $phone = trim($request->input('phone', ''));
        $idcard = trim($request->input('idcard', ''));
        $page = trim($request->input('page', 0)); // 页码
        $pagenumber = trim($request->input('pagenumber', '30')); // 分页个数
        $sql = "select a.id, c.realname,a.phone,c.card_id, b.total_amount,b.balance_amount,b.freeze_amount from mega_member as a left join mega_account as b on a.id=b.member_id left join mega_realname as c on a.id = c.member_id where 1 ";
        $sqlcount = "select count(a.id) as count from mega_member as a left join mega_account as b on a.id=b.member_id left join mega_realname as c on a.id = c.member_id where 1 ";
        $param = array();
        $sqlwhere = '';
        if ($idcard) {
            $sqlwhere .= " and c.card_id=:card_id ";
            $param[':card_id'] = $idcard;
        }
        if ($name) {
            $name = "%$name%";
            $sqlwhere .= " and c.realname like :realname ";
            $param[':realname'] = $name;
        }
        if ($phone) {
            $sqlwhere .= " and a.phone=:phone ";
            $param[':phone'] = $phone;
        }
        $start = $page * $pagenumber;
        $limit = " limit $start, $pagenumber ";
        $results = DB::select($sql . $sqlwhere . $limit, $param);
        $count = DB::select($sqlcount . $sqlwhere, $param);
        
        $data = array(
            'count' => $count[0]->count,
            'items' => $results,
            'page' => $page
        );
        
        $this->output($data);
    }

    /**
     * 余额变动明细
     *
     * @param Request $request
     */
    public function detail(Request $request)
    {
        $page = trim($request->input('page', 0)); // 页码
        $pagenumber = trim($request->input('pagenumber', '30')); // 分页个数
        $start = trim($request->input('start', ''));
        $end = trim($request->input('end', ''));
        $type = trim($request->input('type', ''));
        $amount_type = trim($request->input('amount_type', ''));
        $member_id = trim($request->input('member_id', ''));
        $param = array();
        $sqlwhere = '';
        $sql = "select add_time, `type`, amount_money, remark, amount_type from mega_account_log where member_id = :member_id  ";
        $sqlcount = "select count(*) as count from mega_account_log where member_id = :member_id  ";
        $param[':member_id'] = $member_id;
        if ($type) {
            $sqlwhere .= " and `type` = :type ";
            $param[':type'] = $type;
        }
        if ($amount_type) {
            $sqlwhere .= " and `amount_type` = ':amount_type' ";
            $param[':amount_type'] = $amount_type;
        }
        if ($start) {
            $sqlwhere .= " and `add_time` >= :start_time ";
            $param[':start_time'] = strtotime($start);
        }
        if ($end) {
            $end .= ' 23:59:59';
            $sqlwhere .= " and `add_time` <= :end_time ";
            $param[':end_time'] = strtotime($end);
        }
        
        $start = $page * $pagenumber;
        $limit = " order by id desc limit $start, $pagenumber ";
        
        $results = DB::select($sql . $sqlwhere . $limit, $param);
        $count = DB::select($sqlcount . $sqlwhere, $param);
        $this->output(array(
            'count' => $count[0]->count,
            'items' => $results,
            'page' => $page
        ));
    }

    /**
     * 调整用户余额
     */
    public function updateMoney(Request $request)
    {
        $member_id = trim($request->input('member_id', ''));
        $money = trim($request->input('money', ''));
        $type = trim($request->input('type', ''));
        $remark = trim($request->input('remark', ''));
        $money = (float) $money;
        if ($money <= 0) {
            $this->err('金额错误，需要大于0');
        }
        if ($type == 1) {
            $member = Member::find($member_id);
            $repay_id = updateAccountLog($member->id, $member->name, $money, '后台-增加-' . $remark, 8);
            $this->output(array(), '余额增加成功');
        } elseif ($type == 2) {
            $member = Member::find($member_id);
            $repay_id = updateAccountLog($member->id, $member->name, $money, '后台-减少-' . $remark, 9);
            $this->output(array(), '余额减少成功');
        } else {
            $this->err('类型错误，1增加，2减少');
        }
    }

    public function rechargelog(Request $request)
    {
        $name = trim($request->input('name', ''));
        $phone = trim($request->input('phone', ''));
        $idcard = trim($request->input('idcard', ''));
        $amount = trim($request->input('amount', '')); // 金额
        $start = trim($request->input('start', ''));
        $end = trim($request->input('end', ''));
        $page = trim($request->input('page', 0)); // 页码
        $pagenumber = trim($request->input('pagenumber', '30')); // 分页个数
        
        $sql = "select c.realname,a.phone,c.card_id, b.amount,b.add_time from mega_member as a inner join mega_account_recharge as b on a.id=b.member_id left join mega_realname as c on a.id = c.member_id where b.status = 1 ";
        $sqlcount = "select count(a.id) as count from mega_member as a inner join mega_account_recharge as b on a.id=b.member_id left join mega_realname as c on a.id = c.member_id where b.status = 1 ";
        $param = array();
        $sqlwhere = '';
        if ($idcard) {
            $sqlwhere .= " and c.card_id=:card_id ";
            $param[':card_id'] = $idcard;
        }
        if ($name) {
            $name = "%$name%";
            $sqlwhere .= " and c.realname like :realname ";
            $param[':realname'] = $name;
        }
        if ($phone) {
            $sqlwhere .= " and a.phone=:phone ";
            $param[':phone'] = $phone;
        }
        if ($amount) {
            $sqlwhere .= " and b.amount=:amount ";
            $param[':amount'] = $amount;
        }
        if ($start) {
            $sqlwhere .= " and b.add_time >= :start_time ";
            $param[':start_time'] = strtotime($start);
        }
        if ($end) {
            $end .= ' 23:59:59';
            $sqlwhere .= " and b.add_time <= :end_time ";
            $param[':end_time'] = strtotime($end);
        }
        $start = $page * $pagenumber;
        $limit = " order by b.id desc limit $start, $pagenumber ";
        $results = DB::select($sql . $sqlwhere . $limit, $param);
        $count = DB::select($sqlcount . $sqlwhere, $param);
        
        $resultsNew = array();
        
        foreach ($results as $item) {
            $item->date = date('Y-m-d', $item->add_time);
            $resultsNew[] = $item;
        }
        
        $data = array(
            'count' => $count[0]->count,
            'items' => $results,
            'page' => $page
        );
        
        $this->output($data);
    }

    // 提现记录
    public function withdraw(Request $request)
    {
        $name = trim($request->input('name', ''));
        $phone = trim($request->input('phone', ''));
        $idcard = trim($request->input('idcard', ''));
        $status = trim($request->input('status', ''));
        $amount = trim($request->input('amount', '')); // 金额
        $start = trim($request->input('start', ''));
        $end = trim($request->input('end', ''));
        $page = trim($request->input('page', 0)); // 页码
        $pagenumber = trim($request->input('pagenumber', '30')); // 分页个数
        
        $sql = "select c.realname,a.phone,c.card_id, b.amount,b.created_at,b.bank_name,b.realname,b.status from mega_member as a inner join mega_withdraw as b on a.id=b.member_id left join mega_realname as c on a.id = c.member_id where b.is_shop = 0  ";
        $sqlcount = "select count(a.id) as count from mega_member as a inner join mega_withdraw as b on a.id=b.member_id left join mega_realname as c on a.id = c.member_id where  b.is_shop = 0 ";
        $param = array();
        $sqlwhere = '';
        if ($status) {
            $sqlwhere .= " and b.status=:status ";
            $param[':status'] = $status;
        }
        if ($idcard) {
            $sqlwhere .= " and c.card_id=:card_id ";
            $param[':card_id'] = $idcard;
        }
        if ($name) {
            $name = "%$name%";
            $sqlwhere .= " and c.realname like :realname ";
            $param[':realname'] = $name;
        }
        if ($phone) {
            $sqlwhere .= " and a.phone=:phone ";
            $param[':phone'] = $phone;
        }
        if ($amount) {
            $sqlwhere .= " and b.amount=:amount ";
            $param[':amount'] = $amount;
        }
        if ($start) {
            $sqlwhere .= " and b.created_at >= :start_time ";
            $param[':start_time'] = strtotime($start);
        }
        if ($end) {
            $end .= ' 23:59:59';
            $sqlwhere .= " and b.created_at <= :end_time ";
            $param[':end_time'] = strtotime($end);
        }
        $start = $page * $pagenumber;
        $limit = " order by b.id desc limit $start, $pagenumber ";
        $results = DB::select($sql . $sqlwhere . $limit, $param);
        $count = DB::select($sqlcount . $sqlwhere, $param);
        
        $resultsNew = array();
        
        foreach ($results as $item) {
            $item->date = substr($item->created_at, 0, 10);
            $resultsNew[] = $item;
        }
        
        $data = array(
            'count' => $count[0]->count,
            'items' => $results,
            'page' => $page
        );
        
        $this->output($data);
    }

    // 提现申请
    public function prewithdraw(Request $request)
    {
        $name = trim($request->input('name', ''));
        $phone = trim($request->input('phone', ''));
        $idcard = trim($request->input('idcard', ''));
        $amount = trim($request->input('amount', '')); // 金额
        $start = trim($request->input('start', ''));
        $end = trim($request->input('end', ''));
        $page = trim($request->input('page', 0)); // 页码
        $pagenumber = trim($request->input('pagenumber', '30')); // 分页个数
        
        $sql = "select b.id,c.realname,a.phone,c.card_id, b.amount,b.created_at,b.bank_name,b.realname from mega_member as a inner join mega_withdraw as b on a.id=b.member_id left join mega_realname as c on a.id = c.member_id where b.status = 1 ";
        $sqlcount = "select count(a.id) as count from mega_member as a inner join mega_withdraw as b on a.id=b.member_id left join mega_realname as c on a.id = c.member_id where b.status = 1 ";
        $param = array();
        $sqlwhere = '';
        if ($idcard) {
            $sqlwhere .= " and c.card_id=:card_id ";
            $param[':card_id'] = $idcard;
        }
        if ($name) {
            $name = "%$name%";
            $sqlwhere .= " and c.realname like :realname ";
            $param[':realname'] = $name;
        }
        if ($phone) {
            $sqlwhere .= " and a.phone=:phone ";
            $param[':phone'] = $phone;
        }
        if ($amount) {
            $sqlwhere .= " and b.amount=:amount ";
            $param[':amount'] = $amount;
        }
        if ($start) {
            $sqlwhere .= " and b.created_at >= :start_time ";
            $param[':start_time'] = strtotime($start);
        }
        if ($end) {
            $end .= ' 23:59:59';
            $sqlwhere .= " and b.created_at <= :end_time ";
            $param[':end_time'] = strtotime($end);
        }
        $start = $page * $pagenumber;
        $limit = " order by b.id desc limit $start, $pagenumber ";
        $results = DB::select($sql . $sqlwhere . $limit, $param);
        $count = DB::select($sqlcount . $sqlwhere, $param);
        
        $resultsNew = array();
        
        foreach ($results as $item) {
            $item->date = substr($item->created_at, 0, 10);
            $resultsNew[] = $item;
        }
        
        $data = array(
            'count' => $count[0]->count,
            'items' => $results,
            'page' => $page
        );
        
        $this->output($data);
    }

    public function withrawShenhe(Request $request)
    {
        $id = (int) $request->input('id');
        $adminid = (int) $request->input('adminid');
        $pass = (int) $request->input('pass'); // 1通过，2 不通过
        
        $withRaw = Withdraw::where('id', $id)->first();
        if ($withRaw->status != 1 && $withRaw->status != 7) {
            $this->err('已审核，请勿重复审核');
        }
        $withRaw->admin_id = $adminid;
        $withRaw->shenhe_at = date('Y-m-d H:i:s');
        if (1 == $pass) {
            if ($withRaw->status != 7) {
                // 基本信息校验开始
                $has = Withdraw::where('old_amount', $withRaw->old_amount)->where('status', 4)->first();
                if ($has) {
                    $this->err('该条提现申请需要开发核对数据1');
                }
                $has = Withdraw::where('created_at', $withRaw->created_at)->where('member_id', $withRaw->member_id)->first();
                if ($has) {
                    $this->err('该条提现申请需要开发核对数据2');
                }
                $account = Account::where('member_id', $withRaw->member_id)->frist();
                if (! $account) {
                    $this->err('该条提现申请需要开发核对数据3');
                }
                if ($account->balance_amount <= 0 || $account->total_amount != $account->balance_amount + $account->freeze_amount) {
                    $this->err('该条提现申请需要开发核对数据4');
                }
                // 基本信息校验完成
                
                // 校验总的支付和支出--开始
                $totalPay = AliPreBuy::where('member_id', $withRaw->member_id)->where('status', 1)->sum('amount');
                $totalTixian = Withdraw::where('member_id', $withRaw->member_id)->where('status', 4)->sum('amount');
                if ($totalTixian + $withRaw->amount > $totalPay) {
                    $this->err('该条提现申请需要开发核对数据5');
                }
                // 校验总的支付和支出--结束
            }
            
            $withRaw->status = 2;
            $withRaw->save();
            // /执行代付开始
            $withRaw->batchname = '';
            $withRaw->batchno = $id . '000001000' . $id;
            $withRaw->merinsid = 0;
            $withRaw->save();
            $aliTixian = new AliTiXian();
            list ($payRequestResult, $msg) = $aliTixian->Pay($withRaw->realname, $withRaw->alipay_account, $withRaw->amount, $withRaw->batchno, $withRaw->id);
            if ($payRequestResult) {
                $withRaw->status = 4; // 成功
                $withRaw->save();
                $client = Realname::where('member_id', $withRaw->member_id)->first();
                //用户 设置用户支付宝默认账号
                if(!$client->alipay_account){
                    $client->alipay_account = $withRaw->alipay_account;
                    $client->save();
                }
                if ($withRaw->is_shop == 1) {
                    // 加入商铺端资金日志
                    
                    $shophistory = new ShopHistory();
                    $shophistory->shop_id = $withRaw->member_id;
                    $shophistory->client_member_id = $withRaw->member_id;
                    $shophistory->client_name = $withRaw->realname;
                    $shophistory->client_phone = $client->phone;
                    $shophistory->trans_no = $withRaw->batchno;
                    $shophistory->amount = $withRaw->amount;
                    $shophistory->channel = "支付宝";
                    $shophistory->type = "提现";
                    $shophistory->save();
                }
            } else {
                $withRaw->status = 5; // 易通失败
                $withRaw->comments = $msg;
                $withRaw->save();
                // 退钱给用户
                self::tixianFaild($withRaw->id);
            }
            // /执行代付结束
        } else {
            $withRaw->status = 6;
            $withRaw->save();
            // 退钱给用户
            self::tixianFaild($withRaw->id);
        }
        $this->output(array(
            'status' => $withRaw->status
        ));
    }

    /*
     * public function withrawShenheOld_yitong(Request $request)
     * {
     * $id = (int) $request->input('id');
     * $adminid = (int) $request->input('adminid');
     * $pass = (int) $request->input('pass'); // 1通过，2 不通过
     *
     * // $id=2;
     * // $adminid=1;
     * // $pass=1;
     *
     * $withRaw = Withdraw::where('id', $id)->where('status', 1)->first();
     * if (! $withRaw) {
     * $this->err('已审核');
     * }
     * $withRaw->admin_id = $adminid;
     * $withRaw->shenhe_at = date('Y-m-d H:i:s');
     * if (1 == $pass) {
     * $withRaw->status = 2;
     * $withRaw->save();
     * // /执行代付开始
     * $withRaw->batchname = 'lmj' . time() . rand(111, 999);
     * $withRaw->batchno = rand(10000000, 99999999);
     * $withRaw->merinsid = rand(1000000000, 9999999999);
     * $withRaw->save();
     * $daifu = new Daifu();
     * $result = $daifu->daifuDo($withRaw->batchname, $withRaw->batchno, $withRaw->amount, $withRaw->merinsid, $withRaw->account, $withRaw->realname, $withRaw->bank_name); // 开户行不写会报错
     * if ($result) {
     * $withRaw->status = 3; // 易通受理成功
     * $withRaw->save();
     *
     * if ($withRaw->is_shop == 0) {
     * // 加入商铺端资金日志
     * $client = Realname::where('member_id', $withRaw->member_id)->first();
     * $shophistory = new ShopHistory();
     * $shophistory->shop_id = $withRaw->member_id;
     * $shophistory->client_member_id = $withRaw->member_id;
     * $shophistory->client_name = $withRaw->realname;
     * $shophistory->client_phone = $client->phone;
     * $shophistory->trans_no = $withRaw->batchno;
     * $shophistory->amount = $withRaw->amount;
     * $shophistory->channel = "银行卡";
     * $shophistory->type = "提现";
     * $shophistory->save();
     * }
     * } else {
     * $withRaw->status = 5; // 易通失败
     * $withRaw->save();
     * // 退钱给用户
     * self::tixianFaild($withRaw->id);
     * }
     * // /执行代付结束
     * } else {
     * $withRaw->status = 6;
     * $withRaw->save();
     * // 退钱给用户
     * self::tixianFaild($withRaw->id);
     * }
     * $this->output(array(
     * 'status' => $withRaw->status
     * ));
     * }
     */
    /**
     * 查询提现结果
     */
    public static function withRawQuery()
    {
        $daifu = new Daifu();
        $ondoWithraws = Withdraw::where('status', 3)->get();
        foreach ($ondoWithraws as $withRaw) {
            $result = $daifu->query($withRaw->batchno);
            if ($result == '05') {
                // 失败
                $withRaw->status = 5; // 易通失败
                $withRaw->save();
                // 退钱给用户
                self::tixianFaild($withRaw->id);
            }
            if ($result == '04') {
                // 成功
                $withRaw->status = 4; // 提现成功
                $withRaw->save();
            }
        }
    }

    // 退钱给用户
    private static function tixianFaild($withrawID)
    {
        $withRaw = Withdraw::where('id', $withrawID)->first();
        if (in_array($withRaw->status, array(
            1,
            2,
            4
        ))) {
            return;
        }
        $memberInfo = Member::find($withRaw->member_id);
        $repay_id = updateAccountLog($withRaw->member_id, $memberInfo['name'], $withRaw->amount + $withRaw->fee, '提现失败退款', 7, 0, 99);
    }
}

